package com.sunyard.utils.wxv3Util;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author ziliang.zhou
 * @version 1.0 2020年9月8日
 */
public class AesUtil {

    public static final int TAG_LENGTH_BIT = 128;

    //public static byte[] aesKey = Config.AES_KEY_APIV3.getBytes(); // APIv3密钥
  /*@Value("${AES_KEY_APIV3}")
  public static String apiV3;

  public static byte[] aesKey =apiV3.getBytes(); // APIv3密钥*/

    public static String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext, String apiV3) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            SecretKeySpec key = new SecretKeySpec(apiV3.getBytes(), "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            cipher.updateAAD(associatedData);
            return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new IllegalArgumentException(e);
        }
    }

}